<template>
  <div class="app-container">
    <el-card style="border-radius: 10px;">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="产品编号" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入产品编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入产品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格型号" prop="specification">
        <el-input
          v-model="queryParams.specification"
          placeholder="请输入规格型号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <div style="height:20px"></div>
    <el-card style="border-radius: 10px;">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['financial:standardCosts:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['financial:standardCosts:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['financial:standardCosts:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['financial:standardCosts:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="standardCostsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品编号" align="center" prop="itemCode" />
      <el-table-column label="产品名称" align="center" prop="itemName" />
      <el-table-column label="创建日期" align="center" prop="createTime" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="产品数量" align="center" prop="quantity" />
      <el-table-column label="成本" align="center" prop="cost" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="产品单位" align="center" prop="unit" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCostAccounting(scope.row)"
            v-hasPermi="['financial:standardCosts:edit']"
          >成本明细</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['financial:standardCosts:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['financial:standardCosts:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>

    <!-- 添加或修改标准成本对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="11" style="margin-right: 20px;"> 
          <el-form-item label="产品编号" prop="itemCode">
            <el-input v-model="form.itemCode" placeholder="请选择产品">
              <el-button
                slot="append"
                @click="handleSelectProduct"
                v-if="optType != 'view' && optType != 'save'"
                icon="el-icon-search"
              ></el-button>
            </el-input>
            <ItemSelect ref="itemSelect" @onSelected="onItemSelected"></ItemSelect>
          </el-form-item>
          <el-form-item label="产品名称" prop="itemName">
            <el-input v-model="form.itemName" readonly placeholder="请选择产品" />
          </el-form-item>
          <el-form-item label="规格型号" prop="specification">
            <el-input v-model="form.specification" readonly placeholder="请选择产品" />
          </el-form-item>
          </el-col>
        <el-col :span="11">
          <el-form-item label="产品单位" prop="unit">
            <el-input v-model="form.unit" readonly placeholder="请选择产品" />
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-col>
      </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看成本明细 -->
    <el-dialog :title="'成本明细'" :visible.sync="openCostAccount" width="1000px" append-to-body>
      <el-descriptions title="">
          <el-descriptions-item label="产品编号">{{proData.itemId}}</el-descriptions-item>
          <el-descriptions-item label="产品名称">{{proData.itemName}}</el-descriptions-item>
          <el-descriptions-item label="规格型号">{{proData.specification}}</el-descriptions-item>
          <el-descriptions-item label="成本">{{proData.cost}}</el-descriptions-item>
      </el-descriptions>
      <el-table :data="costList.items" style="margin-top: 20px;" border>
        <el-table-column label="物料名称" align="center" prop="itemName" :show-overflow-tooltip="true"/>
        <el-table-column label="物料编号" align="center" prop="itemCode" :show-overflow-tooltip="true"/>
        <el-table-column label="材质" align="center" prop="itemMaterial" :show-overflow-tooltip="true"/>
        <el-table-column label="规格型号" align="center" prop="specification" :show-overflow-tooltip="true"/>
        <el-table-column label="单位" align="center" prop="unitOfMeasure" :show-overflow-tooltip="true"/>
        <el-table-column label="使用量" align="center" prop="used" />
        <el-table-column label="单价（元）" align="center" prop="referencePrice" />
        <el-table-column label="成本金额（元）" align="center" prop="total" />
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
import {
  listBomGl,
  getBomGl,
  delBomGl,
  addBomGl,
  updateBomGl,
  getCost,
  updateStatusBasic,
  copyBom
} from "@/api/mes/md/bomgl";
import { listItem, listTree, getConfirmItem } from "@/api/mes/md/bomItem";
import { listStandardCosts, getStandardCosts, delStandardCosts, addStandardCosts, updateStandardCosts } from "@/api/mes/financial/standardCosts";
import ItemSelect from '@/components/itemSelect/single.vue';

export default {
  name: "StandardCosts",
  components: { ItemSelect },
  data() {
    return {
      optType:"",
      bomList: [],
      costList: [],
      proData: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标准成本表格数据
      standardCostsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示成本明细弹出层
      openCostAccount: false,
      // 查询Bom参数
      queryParamsBom: {
        bomCode: null,
        bomName: null,
        itemid: null,
        itemCode: null,
        itemName: null,
        routeCode: null,
        routeName: null,
        ancestors: '0', // 0 表示BOM管理
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemid: null,        
        itemCode: null,        
        itemName: null,        
        specification: null,        
        quantity: 1,        
        cost: null,        
        tenantId: null,        
        unit: null      
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "产品编码不能为空", trigger: "blur" }
        ],        
        itemName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" }
        ]   
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询标准成本列表 */
    getList() {
      this.loading = true;
      listStandardCosts(this.queryParams).then(response => {
        this.standardCostsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleSelectProduct() {
      this.$refs.itemSelect.showFlag = true;
    },
    //物料选择弹出框
    async onItemSelected(obj) {
      if (obj != undefined && obj != null) {
        if(obj.itemOrProduct != "PRODUCT"){
          this.$message({
            message: "请不要选择物料！",
            type: "warning"
          });
        }else{
          
          this.queryParamsBom.itemId = obj.itemId;

          await listBomGl(this.queryParamsBom).then(response => {
            this.bomList = response.rows[0];
          });

          await getCost(this.bomList.bomId, this.bomList.routeId).then(res => {

            // 计算物料成本
            let itemCost = 0;
            res.data.items.some(item => {
              itemCost = Math.round((itemCost + item.total) * 100) / 100;
            })
            this.form.cost = itemCost;

            // 计算工序成本
            // this.processCost = 0;
            // res.data.process.some(item => {
            //   this.processCost = Math.round( (this.processCost + item.price) * 100 ) / 100;
            // })
            // 计算总成本
            // this.totalCost = Math.round((this.itemCost + this.processCost) * 100) / 100;
          })

          this.form.itemId = obj.itemId;
          this.form.itemCode = obj.itemCode;
          this.form.itemName = obj.itemName;
          this.form.specification = obj.specification;
          this.form.unit = obj.unitOfMeasure;

        }
        
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        standardCostId: null,        
        itemid: null,        
        itemCode: null,        
        itemName: null,        
        specification: null,        
        quantity: 1,        
        cost: null,         
        remark: null,        
        unit: null      
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.standardCostId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加标准成本";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const standardCostId = row.standardCostId || this.ids
      getStandardCosts(standardCostId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改标准成本";
      });
    },
    /** 查看成本明细 */
    async handleCostAccounting(data){
       this.openCostAccount = true;

       this.queryParamsBom.itemId = data.itemId;

        await listBomGl(this.queryParamsBom).then(response => {
          this.bomList = response.rows[0];
        });

        await getCost(this.bomList.bomId, this.bomList.routeId).then(res => {
          this.costList = res.data;
           // 计算物料成本
          let itemCost = 0;
          res.data.items.some(item => {
            itemCost = Math.round((itemCost + item.total) * 100) / 100;
          })
          this.proData.itemId = data.itemId;
          this.proData.itemName = data.itemName;
          this.proData.specification = data.specification;
          this.proData.cost = itemCost;
        })

    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.standardCostId != null) {
            updateStandardCosts(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStandardCosts(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const standardCostIds = row.standardCostId || this.ids;
      this.$modal.confirm('是否确认删除标准成本编号为"' + standardCostIds + '"的数据项？').then(function() {
        return delStandardCosts(standardCostIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('financial/standardCosts/export', {
        ...this.queryParams
      }, `standardCosts_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
